import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const moduleA = {
  state: {
    name: 'zhangsan'
  },
  mutations: {
    updateName(state, payload) {
      state.name = payload
    }
  },
  actions: {
    aUpdateName(context) {
      setTimeout(() => {
        context.commit('updateName', 'laowang')
      },1000)
    }
  },
  getters: {
    fullname(state) {
      return state.name + '111'
    },
    fullname2(state, getters, rootstate) {
      return getters.fullname + rootstate.counter
    }
  }
}

const moduleB = {
  state: {},
  mutations: {},
  actions: {},
  getters: {}
}

const store = new Vuex.Store({
  state: {
    counter: 500,
    students: [
      {id: 110, name: 'lv', age: 21},
      {id: 110, name: 'jian', age: 20},
      {id: 110, name: 'chen', age: 18},
      {id: 110, name: 'li', age: 22}
    ],
    info: {id: 138, name: 'haha', age: 38}
  },
  mutations: {
    //mutation中的方法必须是同步函数
    //方法
    increment(state) {
      state.counter++
    },
    decrement(state) {
      state.counter--
    },
    incrementCount(state, count) {
      state.counter += count
    },
    updateInfo(state) {
      // state.info['address'] = '广州'
      // delete state.info.age
      // Vue.set(state.info, 'adress', '广州')
      Vue.delete(state.info, 'age')
    }
  },
  actions: {
    //context上下文
    //1.不太优雅的写法
    // aupdateInfo(context, payload) {
    //   setTimeout(() => {
    //     context.commit('updateInfo')
    //     console.log(payload.message);
    //     payload.success()
    //   }, 1000)
    // }
    //2.优雅的写法
    aupdateInfo(context, payload) {
      return new Promise(resolve => {
        setTimeout(() => {
          context.commit('updateInfo')
          console.log(payload);
          resolve('data')
        }, 1000)
      })

    }
  },
  getters: {
    powerCounter(state) {
      return state.counter * state.counter
    },
    more20stu(state) {
      return state.students.filter(s => s.age > 20)
    },
    moreAgeStu(state) {
      return function(age) {
        return state.students.filter(s => s.age > age)
      }
    }
  },
  modules: {
    a: moduleA,
    b: moduleB
  }

})

export default store
